using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using KnowledgeQA.Core.Interfaces;
using KnowledgeQA.Models.DTOs;

namespace KnowledgeQA.API.Controllers
{
    /// <summary>
    /// AI服务控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class AIController : ControllerBase
    {
        private readonly IAIService _aiService;
        private readonly ILogger<AIController> _logger;

        public AIController(IAIService aiService, ILogger<AIController> logger)
        {
            _aiService = aiService;
            _logger = logger;
        }

        /// <summary>
        /// 检查AI服务状态
        /// </summary>
        /// <returns>服务状态</returns>
        [HttpGet("status")]
        public async Task<ActionResult<object>> GetStatus()
        {
            try
            {
                var isAvailable = await _aiService.IsAvailableAsync();
                
                var status = new
                {
                    IsAvailable = isAvailable,
                    ModelName = _aiService.ModelName,
                    Timestamp = DateTime.UtcNow
                };

                return Ok(BaseResponse<object>.SuccessResult(status));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查AI服务状态失败");
                return StatusCode(500, BaseResponse<object>.ErrorResult("检查AI服务状态失败"));
            }
        }

        /// <summary>
        /// 测试AI回答生成
        /// </summary>
        /// <param name="request">测试请求</param>
        /// <returns>AI回答</returns>
        [HttpPost("test-answer")]
        public async Task<ActionResult<AIResponse>> TestAnswer([FromBody] TestAnswerRequest request)
        {
            try
            {
                var response = await _aiService.GenerateAnswerAsync(
                    request.Prompt,
                    request.Context,
                    request.Parameters
                );

                return Ok(BaseResponse<AIResponse>.SuccessResult(response));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试AI回答生成失败");
                return StatusCode(500, BaseResponse<AIResponse>.ErrorResult("测试AI回答生成失败"));
            }
        }

        /// <summary>
        /// 测试向量嵌入生成
        /// </summary>
        /// <param name="request">测试请求</param>
        /// <returns>向量嵌入</returns>
        [HttpPost("test-embedding")]
        public async Task<ActionResult<object>> TestEmbedding([FromBody] TestEmbeddingRequest request)
        {
            try
            {
                var embedding = await _aiService.GenerateEmbeddingAsync(request.Text);
                
                var result = new
                {
                    Text = request.Text,
                    EmbeddingLength = embedding.Length,
                    EmbeddingPreview = embedding.Take(10).ToArray(), // 只显示前10个值
                    Timestamp = DateTime.UtcNow
                };

                return Ok(BaseResponse<object>.SuccessResult(result));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试向量嵌入生成失败");
                return StatusCode(500, BaseResponse<object>.ErrorResult("测试向量嵌入生成失败"));
            }
        }

        /// <summary>
        /// 测试文本相似度计算
        /// </summary>
        /// <param name="request">测试请求</param>
        /// <returns>相似度分数</returns>
        [HttpPost("test-similarity")]
        public async Task<ActionResult<object>> TestSimilarity([FromBody] TestSimilarityRequest request)
        {
            try
            {
                var similarity = await _aiService.CalculateSimilarityAsync(request.Text1, request.Text2);
                
                var result = new
                {
                    Text1 = request.Text1,
                    Text2 = request.Text2,
                    SimilarityScore = similarity,
                    Timestamp = DateTime.UtcNow
                };

                return Ok(BaseResponse<object>.SuccessResult(result));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试文本相似度计算失败");
                return StatusCode(500, BaseResponse<object>.ErrorResult("测试文本相似度计算失败"));
            }
        }

        /// <summary>
        /// 批量测试向量嵌入生成
        /// </summary>
        /// <param name="request">批量测试请求</param>
        /// <returns>批量向量嵌入</returns>
        [HttpPost("test-embeddings")]
        public async Task<ActionResult<object>> TestEmbeddings([FromBody] TestEmbeddingsRequest request)
        {
            try
            {
                var embeddings = await _aiService.GenerateEmbeddingsAsync(request.Texts);
                
                var results = new List<object>();
                for (int i = 0; i < request.Texts.Count; i++)
                {
                    results.Add(new
                    {
                        Text = request.Texts[i],
                        EmbeddingLength = embeddings[i].Length,
                        EmbeddingPreview = embeddings[i].Take(5).ToArray() // 只显示前5个值
                    });
                }

                var result = new
                {
                    TotalTexts = request.Texts.Count,
                    Results = results,
                    Timestamp = DateTime.UtcNow
                };

                return Ok(BaseResponse<object>.SuccessResult(result));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量测试向量嵌入生成失败");
                return StatusCode(500, BaseResponse<object>.ErrorResult("批量测试向量嵌入生成失败"));
            }
        }
    }

    /// <summary>
    /// 测试AI回答请求
    /// </summary>
    public class TestAnswerRequest
    {
        /// <summary>
        /// 提示词
        /// </summary>
        public string Prompt { get; set; } = string.Empty;

        /// <summary>
        /// 上下文
        /// </summary>
        public string? Context { get; set; }

        /// <summary>
        /// 模型参数
        /// </summary>
        public Dictionary<string, object>? Parameters { get; set; }
    }

    /// <summary>
    /// 测试向量嵌入请求
    /// </summary>
    public class TestEmbeddingRequest
    {
        /// <summary>
        /// 文本内容
        /// </summary>
        public string Text { get; set; } = string.Empty;
    }

    /// <summary>
    /// 测试文本相似度请求
    /// </summary>
    public class TestSimilarityRequest
    {
        /// <summary>
        /// 文本1
        /// </summary>
        public string Text1 { get; set; } = string.Empty;

        /// <summary>
        /// 文本2
        /// </summary>
        public string Text2 { get; set; } = string.Empty;
    }

    /// <summary>
    /// 批量测试向量嵌入请求
    /// </summary>
    public class TestEmbeddingsRequest
    {
        /// <summary>
        /// 文本列表
        /// </summary>
        public List<string> Texts { get; set; } = new List<string>();
    }
} 